package cv.cvs.controller;

import com.sun.org.apache.regexp.internal.RE;
import cv.cvs.entity.Userinfo;
import cv.cvs.vo.RestVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/upload")
public class UserController {

    @GetMapping("/hello")
    public String index(Model model){
        model.addAttribute("sex","女");
        model.addAttribute("city","shanghai");
        model.addAttribute("nowTime",new Date());

        Userinfo user1=new Userinfo(1,"李白","123");
        Userinfo user2=new Userinfo(2,"杜甫","123");
        List<Userinfo> users=new ArrayList<>();
        users.add(user1);
        users.add(user2);
        model.addAttribute("users",users);

        return "hello";
    }


    @Value("${web.upload-path}")
    private String path;
    @PostMapping()
    public RestVo saveOrUpdate(MultipartFile file){
        if (!file.isEmpty()) {
            if (file.getSize()>500*1024) {
                return RestVo.erorr("文件超过500k");
            }
            String originalFilename = file.getOriginalFilename();
            String format = originalFilename.substring(originalFilename.lastIndexOf("."));

            if(
                    format.equalsIgnoreCase(".jpg")||
                            format.equalsIgnoreCase(".jpeg")||
                            format.equalsIgnoreCase(".png")||
                            format.equalsIgnoreCase(".gif")
            ){
                String fileName  = String.valueOf(System.currentTimeMillis());
                File file1 = new File(path+fileName+format);
                try {
                    file.transferTo(file1);
                    return RestVo.success("文件上传成功",fileName+format);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return RestVo.erorr("文件格式不正确");
        } else {
            return RestVo.erorr("文件未上传");
        }
    }
}
